/**
 * @author khathirdstep1025.
 * 16/05/2013.
 * Copyright (c) 2013 - 2014.
 */


package com.kha;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Opt1Servlet.
 * Resonsible for handle form WelcomeServlet.htm.
 */
@WebServlet("/Opt1Servlet")
public class Opt1Servlet extends HttpServlet {
	
	// Constants
	static final String EMPTY = "";
	
	/**
	 * Serial Version UID.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Handle GET invocation.
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Do nothing.
		// For convenient, redirect to doPost method.
		
		doPost(request, response);
	}

	/**
	 * Handle POST invocation.
	 * 
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String refererURL = null;

		// Get referer URL.
	
		refererURL = request.getHeader("Referer");

		if (refererURL != null) {
			String[] urlElements = refererURL.split("/");
			String pageURL = urlElements[urlElements.length - 1];

			if (!pageURL.equals("WelcomeServlet.html")) {

				// Redirect to error page.
				response.sendRedirect("Error.html");
				return;
			}

		} else {
			
			// Redirect to homepage.
			response.sendRedirect("/");
			return;
		}
		
		// Get parameter first and last name.
		String txtFirstName = request.getParameter("txtFirstName");
		
		// Not necessary, commented by now.
		//String txtLastName = request.getParameter("txtLastName");

		// Generate HTML if firstname is valid.
		if (txtFirstName != null && !EMPTY.equals(txtFirstName.trim())) {

			// Preparation
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();

			// Write HTML.
			out.println("<h1>Welcome, " + txtFirstName.trim() + "!</h1>");

			// Finish writing HTML.
			out.close();

		} else {

			// Redirect to Welcome page if first name is invalid.
			response.sendRedirect("WelcomeServlet.html");
		}
	}

}
